package com.meng.netty.decoder;

import com.meng.netty.constant.PointOfSaleConstant;
import com.meng.model.PointOfSale;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;


/**
 * POS decoder Netty 自定义解码器
 *
 * @author MENG
 * @version 2018/3/21
 * @see
 */
public class PointOfSaleDecoder extends MessageToMessageDecoder<ByteBuf>
{
    Logger logger = LoggerFactory.getLogger(PointOfSaleDecoder.class);

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception
    {
        //byteBuf.readableBytes() 默认=2
        if(byteBuf.readableBytes() < PointOfSaleConstant.LEAST_PROTOCOL_LENGTH)
        {
            return;
        }

//        System.out.println(byteBuf.readableBytes());

        //头
        byte[] headBytes = new byte[7];

        byteBuf.readBytes(headBytes);

        String head = new String(headBytes);

        //判断消息头
        if(!PointOfSaleConstant.MESSAGE_HEAD.equals(head))
        {
            return;
        }

        PointOfSale pointOfSales = PointOfSale.getPointOfSaleByType(byteBuf,head); //获取解码对象

        if(pointOfSales == null)
        {
            logger.error("消息类型无法识别、无法解码消息体！！！");
        }

        list.add(pointOfSales);
    }
}
